package com.xia.utils;


import com.xia.domain.OperationLog;
import com.xia.domain.User;
import com.xia.rocket.RocketMQProducer;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 有关日志的工具类
 */
@Component
public class LogUtils {

    @Autowired
    private UserUtils userUtils;
    @Autowired
    private RocketMQProducer rocketMQProducer;

    /**
     * 包装操作日志
     */
    public OperationLog wrapLog(User user) {
        // 获取当前操作名称
        String methodName = Thread.currentThread().getStackTrace()[3].getMethodName();
        OperationLog log = new OperationLog();
        log.setUserId(userUtils.getUserByName(user.getUsername()).getUserId());
        log.setAction("用户：" + user.getUsername() + "进行" +  methodName + "成功");
        log.setIp(user.getIp());
        log.setDetail(user.getDetail());
        return log;
    }

    /**
     * 记录日志
     */
    public void recordLog(User user, HttpServletRequest request) {
        // 获取用户Ip地址
        user.setIp(userUtils.getIpAddress(request));
        // 获取用户操作详情
        user.setDetail(userUtils.getUserDetail(user));
        // 调用包装操作日志，将包装好的log传递给RocketMQProducer
        rocketMQProducer.sendOneWayMessage(wrapLog(user));
    }
}
